import os

from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from base import logger
from config import BASE_DIR


class PageBase:
    def __init__(self, driver):
        self.driver = driver

    def fd_element(self, locator, timeout=15):
        """定位单个元素（带显式等待）"""
        try:
            logger.info(f"定位元素: {locator}")
            element = (WebDriverWait(self.driver, timeout)
                       .until(EC.visibility_of_element_located(locator)))
            return element
        except Exception as e:
            logger.error(f"元素定位失败: {locator} - {str(e)}")
            raise

    def fd_elements(self, locator, timeout=15):
        """定位多个元素（带显式等待）"""
        try:
            logger.info(f"定位多个元素: {locator}")
            return WebDriverWait(self.driver, timeout).until(
                EC.visibility_of_all_elements_located(locator))
        except Exception as e:
            logger.error(f"元素组定位失败: {locator} - {str(e)}")
            raise

    def base_click(self, locator):
        """点击元素"""
        logger.info(f"点击元素: {locator}")
        self.fd_element(locator).click()

    def base_input_text(self, locator, text):
        """输入文本"""
        logger.info(f"在元素 {locator} 输入文本: {text}")
        element = self.fd_element(locator)
        element.clear()
        element.send_keys(text)

    def base_get_text(self, locator):
        """获取元素文本"""
        text = self.fd_element(locator).text
        logger.info(f"获取元素文本: {locator} -> {text}")
        return text

    def base_swipe(self, start_x, start_y, end_x, end_y, duration=1000):
        """滑动操作"""
        logger.info(f"滑动操作: ({start_x},{start_y}) -> ({end_x},{end_y})")
        self.driver.swipe(start_x, start_y, end_x, end_y, duration)

    def base_get_toast(self,toast_loc, timeout=10):
        """获取Toast提示文本"""
        try:
            # toast_loc = (By.XPATH, '//android.widget.Toast[1]')
            toast = WebDriverWait(self.driver, timeout).until(
                EC.presence_of_element_located(toast_loc))
            text = toast.text
            logger.info(f"获取Toast提示: {text}")
            return text
        except Exception as e:
            logger.error(f"获取Toast失败: {str(e)}")
            return ""

    def get_shot(self, file_name):
        """
        截图
        :param file_name: 截图文件名
        :return:无
        """
        # self.driver.get_screenshot_as_file(PATH + r"\img\pwd_error.png")
        # self.driver.get_screenshot_as_file(PATH + '/img/' + file_name)
        # 推荐
        file_path = os.path.join(BASE_DIR, 'img', file_name)
        self.driver.get_screenshot_as_file(file_path)

